package com.pr.makfilm.service.util;

import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Barbara
 * Date: 12.10.13
 * Time: 23:34
 * To change this template use File | Settings | File Templates.
 */
public class NumberUtils
{
   private static final String[] ALPHABET = new String[]
           {
                   "A",
                   "B",
                   "C",
                   "D",
                   "E",
                   "F",
                   "G",
                   "H",
                   "I",
                   "J",
                   "K",
                   "L",
                   "M",
                   "N",
                   "O",
                   "P",
                   "R",
                   "S",
                   "T",
                   "U",
                   "W",
                   "Y",
                   "Z"
           };

   public static String toRoman(int arabic)
   {
      LinkedHashMap<String, Integer> roman_numerals = new LinkedHashMap<String, Integer>();
      roman_numerals.put("M", 1000);
      roman_numerals.put("CM", 900);
      roman_numerals.put("D", 500);
      roman_numerals.put("CD", 400);
      roman_numerals.put("C", 100);
      roman_numerals.put("XC", 90);
      roman_numerals.put("L", 50);
      roman_numerals.put("XL", 40);
      roman_numerals.put("X", 10);
      roman_numerals.put("IX", 9);
      roman_numerals.put("V", 5);
      roman_numerals.put("IV", 4);
      roman_numerals.put("I", 1);
      String res = "";
      for (Map.Entry<String, Integer> entry : roman_numerals.entrySet())
      {
         int matches = arabic / entry.getValue();
         res += repeat(entry.getKey(), matches);
         arabic = arabic % entry.getValue();
      }
      return res;
   }

   public static String toAlphabetic(int arabic)
   {
      if (arabic > 0)
      {
         arabic--;
         int len = ALPHABET.length;
         int pos = arabic / len;
         String result = StringUtils.EMPTY;
         if (pos > 0 && pos < len)
         {
            result = ALPHABET[pos - 1];
         }
         pos = arabic % len;
         result += ALPHABET[pos];
         return result;
      }
      return StringUtils.EMPTY;
   }

   private static String repeat(String s, int n)
   {
      if (s == null)
      {
         return null;
      }
      final StringBuilder sb = new StringBuilder();
      for (int i = 0; i < n; i++)
      {
         sb.append(s);
      }
      return sb.toString();
   }
}
